﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using DBControl;
using System.Data.SqlClient;


namespace SellerProject
{
    public partial class iSelgood : TopBasePage
    {
        string strcid;
        List<Top.Api.Domain.Item> Sourcelist;
        private Dictionary<bool ,Func<string,Boolean>> dic;

        protected void Page_Load(object sender, EventArgs e)
        {
            string protrigger =  Request.Form["disOF"];

            strcid = Request.QueryString["cid"];
            string value = Request.Form["hName"] ?? "";
            string nid = Request.Form["hNid"] ?? "";
            bool reslut;
            if (bool.TryParse(value, out reslut) && nid != null)
            {
                dic = new Dictionary<bool,Func<string,bool>>();
                dic.Add(true, Confirm);
                dic.Add(false, Cancel);
                dic[reslut](nid);
            }
            if (!IsPostBack)
            {
                BindGrid(strcid,this.grPager.PageSize,this.grPager.CurrentPageIndex);
            }
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <returns></returns>
        private void getDate(string cid, int pagesize, int pageno)
        {
            ItopInit iinit = new ItopInit();
            if (cid == null)
            {
                iinit.onsellsGet(Session["sessionKey"].ToString(),pagesize,pageno);
                Sourcelist = iinit.onsellres.Items;
            }
            else
            {
                iinit.onsellsGet(Session["sessionKey"].ToString(),pagesize,pageno,cid);
                Sourcelist = iinit.onsellres.Items;
            }
            this.grPager.RecordCount = (int)iinit.onsellres.TotalResults;
        }
        /// <summary>
        /// 绑定数据源
        /// </summary>
        /// <param name="cid"></param>
        private void BindGrid(string cid, int pagesize, int pageno)
        {
            getDate(cid,pagesize,pageno);
            gridvselgood.DataSource = Sourcelist;
            gridvselgood.DataBind();
        }
        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grpager_PageChanged(object sender, EventArgs e)
        {
            BindGrid(strcid, this.grPager.PageSize, this.grPager.CurrentPageIndex);
            ScriptManager.RegisterStartupScript(grPager, this.GetType(), "resizeimg", "<script>ResizeImg();</script>", false);
            ScriptManager.RegisterStartupScript(grPager, this.GetType(), "resizeparentifm", "<script>resizeparentifm();</script>", false);
        }
        /// <summary>
        /// 写入数据库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gridvselgood_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            #region testcode
            //if (e.CommandName == "Del")
            //{
            //    Marketing mk = new Marketing(Session["sessionKey"].ToString());
            //    Bargains mybras = mk.getTaobaoPromotion((mk.getTaobaoGroup(Marketing.GroupName)).GroupID, e.CommandArgument.ToString());
            //    if (mybras != null) { for (int i = 0; i < mybras.Count; i++) { if (mybras[i].End_Date < DateTime.Now) { mk.delPromotion(mybras[i].Bid); } } }
            //    else { mk.delTaobaoGroup((mk.getTaobaoGroup(Marketing.GroupName)).GroupID); }
            //}
            #endregion testcode
            
            if (e.CommandName == "insert")
            {
                DataControlFieldCell dfc = ((e.CommandSource as LinkButton).Parent) as DataControlFieldCell;
                if ((dfc.FindControl("setPromo") as HiddenField).Value == "true")//卖家选择要设置优惠
                {//获取设置优惠需要的值
                    string distype = (dfc.FindControl("disType") as DropDownList).Text;
                    string disvalue;
                    if (distype == "DISCOUNT") { disvalue = (dfc.FindControl("disValue2") as DropDownList).Text; }
                    else { disvalue = (dfc.FindControl("disValue") as TextBox).Text; }
                    double disdate = Convert.ToDouble((dfc.FindControl("disdata") as DropDownList).Text);

                    try
                    {
                        Marketing mk = new Marketing(Session["sessionKey"].ToString());
                        Group mygrp = mk.getGroup(Session["usnick"].ToString());//获取当前用户的人群
                        
                        Bargains mybras = mk.getTaobaoPromotion(mygrp.GroupID, e.CommandArgument.ToString());//查询已存在的优惠信息
                        if (mybras != null)//如果存在优惠信息
                        {
                            for (int i = 0; i < mybras.Count; i++)//遍历优惠信息，检查是否有未过期的
                            {
                                if (mybras[i].Active == "ACTIVE" && mybras[i].End_Date > DateTime.Now)
                                {
                                    TimeSpan ts = new TimeSpan(DateTime.Now.Ticks).Subtract(new TimeSpan(mybras[i].End_Date.Ticks));
                                    string msg = "该商品已经在打折了！还有：" + ts.Days.ToString() + "天" + ts.Hours.ToString() + "小时！<br>您还是要发布这个商品吗？（将沿用以前的优惠）";
                                    ScriptManager.RegisterStartupScript(this, GetType(), "confirm", "CustomSubmit('"+ msg +"')", true);
                                    return;
                                }
                                mk.delPromotion(mybras[i].Bid);//删除淘宝网中已失效的优惠信息
                            }
                            Bargain mybra = mk.addTaobaoPromotion(e.CommandArgument.ToString(), distype, disvalue, DateTime.Now.AddHours(disdate), mygrp.GroupID);
                            execSINFOandPRO(mk, e.CommandArgument.ToString(), mybra);
                        }
                        else
                        {
                            Bargain mybra = mk.addTaobaoPromotion(e.CommandArgument.ToString(), distype, disvalue, DateTime.Now.AddHours(disdate), mygrp.GroupID);
                            execSINFOandPRO(mk, e.CommandArgument.ToString(), mybra);
                        }
                    }
                    catch (Exception err) { jsargs.JavaScriptLocationHref("sell404.aspx?errmsg='" + err.Message.ToString() + "'", Page); }
                }
                else
                {
                    try { execSINFOandPRO(null, e.CommandArgument.ToString(), null); }
                    catch (Exception err) { jsargs.JavaScriptLocationHref("sell404.aspx?errmsg='" + err.Message.ToString() + "'", Page); }
                }
            ScriptManager.RegisterStartupScript(this, this.GetType(), "showResult", "<script>showResult(1);</script>", false);
            ScriptManager.RegisterStartupScript(grPager, this.GetType(), "resizeimg", "<script>ResizeImg();</script>", false);
            }
        }

        private Boolean Confirm(string nid)
        {
            //确认后要添加商品
            try { execSINFOandPRO(null, nid, null); }
            catch (Exception err) { jsargs.JavaScriptLocationHref("sell404.aspx?errmsg='" + err.Message.ToString() + "'", Page); }
            return true;
        }


        private Boolean Cancel(string nid) 
        {
            jsargs.GoHistory(-1, Page);
            return true;
        }

        /// <summary>
        /// 写入sellinfo
        /// </summary>
        /// <param name="mk"></param>
        /// <param name="nid"></param>
        /// <param name="bargain"></param>
        protected void execSINFOandPRO(Marketing mk, string nid, Bargain bargain)
        {
            string uNick = Session["usNick"].ToString();
            System.Guid gubinfo = new Guid(Request.QueryString["binfo"]);
            ItopInit iinit = new ItopInit();
            iinit.itemGet(Session["sessionKey"].ToString(), nid, uNick);
            iinit.usCreditGet(uNick, Session["sessionKey"].ToString());
            SqlParameter[] sps = {new SqlParameter("@buyerid", gubinfo), 
                                    new SqlParameter("@releasename",uNick),
                                    new SqlParameter("@tradelink",iinit.itemgetres.Item.DetailUrl),
                                    new SqlParameter("@infomation", iinit.itemgetres.Item.Title),
                                    new SqlParameter("@piclink", iinit.itemgetres.Item.PicUrl),
                                    new SqlParameter("@cate", iinit.itemgetres.Item.Cid),
                                    new SqlParameter("@honor", iinit.usellercredit.Level),
                                    new SqlParameter("@price", iinit.itemgetres.Item.Price),
                                    new SqlParameter("@city", iinit.itemgetres.Item.Location.City),
                                    new SqlParameter("@state", iinit.itemgetres.Item.Location.State),
                                    new SqlParameter("@sellid", SqlDbType.UniqueIdentifier)};
            sps[10].Direction = ParameterDirection.Output;
            SqlDbHelper sdh = new SqlDbHelper();
            //num_iid,title,price,detail_url,type,pic_url,num,stuff_status,post_fee,express_fee,ems_fee,score,item_imgs.url
            sdh.ExecuteNonQuery("ChangeSellerInfoR", CommandType.StoredProcedure, sps);
            if (mk != null && bargain != null) { mk.addPromotion(bargain, new Guid(sps[10].Value.ToString())); }
        }


        //添加ddl默认值
        protected void gridvselgood_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DropDownList disValue = (e.Row.FindControl("disValue2")) as DropDownList;
                for (int i = 99; i > 1; i--)
                {
                    float fi = i;
                    disValue.Items.Add(new ListItem((fi/10).ToString() + "折", (fi/10).ToString()));
                }
            }
        }
    }
}